package cn.ex.de001.common.utils;

import cn.ex.de001.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/***
 * 下载文件
 */
@Slf4j
public class DownloadFile {
    public static Boolean downloadFile(String fileURL, String savePath){
        try {
            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedInputStream in = new BufferedInputStream(httpConn.getInputStream());
                FileOutputStream out = new FileOutputStream(savePath);
                byte[] buffer = new byte[1024];
                int bytesRead = -1;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                out.close();
                in.close();
                log.info("保存路径: " + savePath);
                return true;
            } else {
                log.info("下载失败: " + responseCode);
            }
            //终止HTTP连接
            httpConn.disconnect();
        } catch (IOException e) {
            throw new BaseException(e.getMessage());
        }
        return false;
    }

    /**
     *
     * @param fileURL 文件路径
     * @param savePath  保存路径
     * @param maxRetries  下载次数
     * @param retryDelaySeconds  延迟秒数
     * @return
     */
    public static Boolean downloadFileWithRetry(String fileURL, String savePath, int maxRetries, int retryDelaySeconds) {
        int attempt = 0;
        while (attempt < maxRetries) {
            try {
                URL url = new URL(fileURL);
                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                int responseCode = httpConn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    try (BufferedInputStream in = new BufferedInputStream(httpConn.getInputStream());
                         FileOutputStream out = new FileOutputStream(savePath)) {
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = in.read(buffer)) != -1) {
                            out.write(buffer, 0, bytesRead);
                        }
                    }
                    log.info("文件已成功下载到: " + savePath);
                    // 成功下载后关闭连接
                    httpConn.disconnect();
                    return true;
                } else {
                    log.warn("下载失败，响应码: " + responseCode);
                }
                // 终止HTTP连接
                httpConn.disconnect();
            } catch (IOException e) {
                log.error("下载文件时发生错误: " + e.getMessage(), e);
            }
            // 如果不是最后一次尝试，则等待指定的时间后再试
            if (attempt < maxRetries - 1) {
                log.info("尝试 " + (attempt + 1) + " 失败，将在 " + retryDelaySeconds + " 秒后重试...");
                try {
                    Thread.sleep(retryDelaySeconds * 1000L);
                } catch (InterruptedException ie) {
                    log.error("线程休眠被中断", ie);
                    Thread.currentThread().interrupt();
                }
            }
            attempt++;
        }
        log.error("达到最大重试次数，下载仍未成功");
        return false;
    }


    // 将 File 转换为 MultipartFile
    public static MultipartFile convertFileToMultipartFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        return new MockMultipartFile(file.getName(), file.getName(), "application/pdf", inputStream);
    }

    //时间转换
    public static Date dateTime(String time, String dateFormat){
        Date parse = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            parse = sdf.parse(time);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return parse;
    }


    //压缩文件
    public static void compressFile(String sourceFilePath, String zipFilePath) {
        try {
            FileOutputStream fos = new FileOutputStream(zipFilePath);
            ZipOutputStream zos = new ZipOutputStream(fos);
            File fileToZip = new File(sourceFilePath);
            FileInputStream fis = new FileInputStream(fileToZip);
            ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
            zos.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zos.write(bytes, 0, length);
            }
            zos.closeEntry();
            zos.close();
            fis.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //判断系统
    public static String getSystem(){
        String os = System.getProperty("os.name").toLowerCase();
        String  system = "";
        if (os.contains("win")) {
            system = "Windows";
        } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
            system = "Linux";
        } else {
            system = "不清楚";
        }
        return system;
    }


    public static void main(String[] args) {
        //String fileURL = "https://static-data.eol.cn/upload/schooljobreport/20240515/1715742390_5600.pdf";
        //String savePath = "D:\\IDEA_moudel\\apollo\\apollo-service\\src\\main\\resources\\static\\downloaded_file.pdf";
        // String fileURL = "https://static-file.daxue.cn/kungfu-org/production/avatar/2f83bfe018124ed79954a9c070c49767.jpeg";
        // String ur = "https://cdn2.suno.ai/image_8872b3f0-2ec7-42f9-9968-03481632a117.jpeg";
        //  String mp = "https://cdn1.suno.ai/8872b3f0-2ec7-42f9-9968-03481632a117.mp4";
        //String fileName = extractFileNameFromURL(mp);
        //String extension = getFileExtension(fileName);
        //String fileNameFrom = getFileExtension(ur);
        //String savePath = "D:\\IDEA_moudel\\apollo\\apollo-service\\src\\main\\resources\\static\\downloaded.jpeg";
        //Boolean b = downloadFile(fileURL, savePath);
        //System.out.println(fileName);
        //System.out.println(extension);
        //System.out.println(fileNameFrom);

      /*  String savePath = "D:\\IDEA_moudel\\apollo\\apollo-service\\src\\main\\resources\\file\\casual\\ffa359a7dfea.avi";
        String fileURL = "http://vibktprfx-prod-prod-damo-eas-cn-shanghai.oss-cn-shanghai.aliyuncs.com/eas-recolor-hd/dySkyHair_f392cdce-ab5e-4c50-9570-ffa359a7dfea.avi?Expires=1729856466&OSSAccessKeyId=LTAI4FoLmvQ9urWXgSRpDvh1&Signature=RLjpJTooGswkBY0Vwmq1wIKp%2Bmc%3D";
        Boolean b = downloadFile(fileURL, savePath);
        System.out.println(b);*/

        String url = "http://su.bcebos.com/v1/creative-brain-hd/multimedia/7D3870FA9229489C9A6CA827814C0BC7/creation_1730267105164_676.mp4?authorization=bce-auth-v1%2FALTAKPxUA3jj8b35CQnomxZGQN%2F2024-10-30T05%3A45%3A06Z%2F604800%2F%2Fa6a266bfe5edbddb1617ec61456d3093a11152943e55664fa284fe8b73db62f1";
        String string = extractFileNameFromURL(url);
        System.out.println(string);
    }

    public static String extractFileNameFromURL(String urlString) {  //获取  image_8872b3f0-2ec7-42f9-9968-03481632a117.jpeg
        try {
            URL url = new URL(urlString);
            String path = url.getPath();
            String[] pathParts = path.split("/");
            return pathParts[pathParts.length - 1];
        } catch (MalformedURLException e) {
            System.err.println("Invalid URL: " + e.getMessage());
            return e.getMessage();
        }
    }

    public static String getFileExtension(String fileName) {  // 获取 jpeg
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex == -1) {
            return "";
        }
        return fileName.substring(lastDotIndex+1);
    }

    public static String getFileNameFrom(String urlString){  //获取  mp4
        String[] tokens = urlString.split("\\.");
        String extension = tokens[tokens.length - 1];
        return extension;
    }

}

